package com.lyfei.yd.admin.security.config;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

@Configuration
public class CorsFilterConfig {
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "HEAD", "DELETE", "OPTION"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.addExposedHeader("Authorization");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    public CorsFilter corsFilter() {
        DefaultCorsFilter defaultCorsFilter = new DefaultCorsFilter(corsConfigurationSource());
        return defaultCorsFilter;
    }

    @Getter
    @Setter
    static class DefaultCorsFilter extends CorsFilter implements OrderedFilter {

        /**
         * Constructor accepting a {@link CorsConfigurationSource} used by the filter
         * to find the {@link CorsConfiguration} to use for each incoming request.
         *
         * @param configSource
         * @see UrlBasedCorsConfigurationSource
         */
        public DefaultCorsFilter(CorsConfigurationSource configSource) {
            super(configSource);
        }

        @Override
        public int getOrder() {
            return -104;
        }
    }
}
